package io.github.codelifeleno.jdbrelease;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.FileResource;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.Console;
import io.github.codelifeleno.jdbrelease.config.JDBReleaseConfig;
import io.github.codelifeleno.jdbrelease.execute.JDBReleaseInit;
import io.github.codelifeleno.jdbrelease.execute.JDBReleaseService;
import io.github.codelifeleno.jdbrelease.model.JDBReleaseRunModel;
import io.github.codelifeleno.jdbrelease.util.JDBResourceUtils;
import org.apache.commons.io.FileUtils;
import picocli.CommandLine;

import java.io.File;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;

@CommandLine.Command(name = "jdbrelease", mixinStandardHelpOptions = true, version = "jdbrelease 1.0",
        description = "处理数据库脚本的版本管理过程")
public class CliMain implements Callable<Integer> {

    @CommandLine.ArgGroup(exclusive = true, multiplicity = "1")
    InitOrExecute initOrExecute;

    @CommandLine.Spec
    CommandLine.Model.CommandSpec spec;

    File configDir;

    @CommandLine.Option(names = "-f", required = true, description = "设置配置文件的路径或包含配置文件的路径")
    public void setConfigDir(File configDir) {
        if (!configDir.mkdirs() && !configDir.isDirectory()) {
            throw new CommandLine.ParameterException(spec.commandLine(), "指定的路径并非目录，请重新指定");
        }
        this.configDir = configDir;
    }

    @CommandLine.Option(names = {"-h", "--help"}, usageHelp = true, description = "展示此帮助")
    boolean help;

    static class InitOrExecute {
        @CommandLine.Option(names = "-i", required = true, description = "初始化项目目录的配置")
        boolean isInit = false;
        @CommandLine.Option(names = "-e", required = true, description = "运行脚本版本管理")
        boolean isExecute = false;
    }

    private void validate() {
        if (initOrExecute.isExecute) {
            if (!configDir.canRead() || !configDir.canWrite()) {
                throw new CommandLine.ParameterException(spec.commandLine(), "指定的路径不存在，或文件夹不可读写，请检查并重新处理");
            }
        }
    }

    public static void main(String[] args) {
        int exit = new CommandLine(new CliMain()).execute(args);
        System.exit(exit);
    }

    @Override
    public Integer call() throws Exception {
        if (initOrExecute.isInit) {
            FileUtils.deleteDirectory(configDir);
            configDir.mkdirs();
            List<String> dbConfigs = JDBResourceUtils.findMatchingResources(this.getClass(), "JDBRelease/.*");
            for (String dbConfig : dbConfigs) {
                Console.log(dbConfig);
                JDBResourceUtils.extractResourceToTemp(this.getClass(), dbConfig, Paths.get(configDir.toURI()));
            }
            Console.log("目录处理完成，请检查");
        } else if (initOrExecute.isExecute) {
            File jdbReleaseConfigFile = new File(configDir, "JDBReleaseConfig.xml");
            if (!jdbReleaseConfigFile.exists()) {
                throw new RuntimeException("指定的配置文件不存在: " + jdbReleaseConfigFile);
            }
            String runId = DateUtil.format(new Date(), "yyyyMMdd_HHmm");
            JDBReleaseRunModel runModel = new JDBReleaseRunModel(runId, ResourceUtil.getResourceObj(jdbReleaseConfigFile.getAbsolutePath()));
            JDBReleaseInit init = new JDBReleaseInit();
            JDBReleaseConfig jdbReleaseConfig = init.initConfig(new FileResource(jdbReleaseConfigFile));
            JDBReleaseService jdbReleaseService = new JDBReleaseService(jdbReleaseConfig);
            jdbReleaseService.executeAll(runModel);
        } else {
            Console.log("指定的参数非法，请检查");
            return 1;
        }
        return 0;
    }
}
